package com.liannong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liannong.entity.Order;
import com.liannong.entity.Product;

import com.liannong.mapper.OrderMapper;
import com.liannong.mapper.ProductMapper;

import com.liannong.service.OrderService;
import com.liannong.vo.OrderVO;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ProductMapper productMapper;
    
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer createOrder(Order order) {
        // 保存订单
        this.save(order);
        return order.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(Integer orderId) {
        Order order = this.getById(orderId);
        if (order == null) {
            return false;
        }
        
        // 更新订单状态为已支付
        order.setStatus(1);
        return this.updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Integer orderId) {
        Order order = this.getById(orderId);
        if (order == null) {
            return false;
        }
        
        // 更新订单状态为已取消
        order.setStatus(4);
        return this.updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDeliveryStatus(Integer orderId, boolean toDelivery) {
        Order order = this.getById(orderId);
        if (order == null) {
            return false;
        }
        
        // 检查订单状态是否允许修改配送状态
        // 只有已支付(1)或配送中(2)的订单可以修改配送状态
        if (order.getStatus() != 1 && order.getStatus() != 2) {
            return false;
        }
        
        // 更新订单状态：toDelivery为true时设为配送中(2)，否则设为已支付(1)
        order.setStatus(toDelivery ? 2 : 1);
        return this.updateById(order);
    }

    @Override
    public OrderVO getOrderDetail(Integer orderId) {
        Order order = this.getById(orderId);
        if (order == null) {
            return null;
        }
        
        OrderVO orderVO = convertToOrderVO(order);
        
        // 获取商品名称
        Product product = productMapper.selectById(order.getProductId());
        if (product != null) {
            orderVO.setProductName(product.getName());
        }
        
        return orderVO;
    }

    @Override
    @Transactional(readOnly = true)
    public IPage<OrderVO> findOrdersByUserPermission(
            @Param("userId") Integer userId, 
            @Param("roleId") Integer roleId, 
            @Param("orderNo") String orderNo, 
            @Param("pageNum") Integer pageNum, 
            @Param("pageSize") Integer pageSize) {
            
        System.out.println("查询参数 - userId: " + userId + ", roleId: " + roleId + ", orderNo: " + orderNo);
        
        Page<Order> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        
        // 根据角色权限设置查询条件
        // 角色ID为1或2的是管理员，可以查看所有订单
        // 角色ID为3的普通用户只能查看自己的订单
        if (roleId == null || (roleId != 1 && roleId != 2)) {
            queryWrapper.eq("user_id", userId);
        }
     
        // 如果提供了订单号，添加订单号过滤条件
        if (orderNo != null && !orderNo.isEmpty()) {
            // 只使用订单ID进行查询
            queryWrapper.like("id", orderNo);
        }
        
        // 按创建时间倒序
        queryWrapper.orderByDesc("create_time");
        
        // 打印SQL语句
        System.out.println("订单查询SQL: " + queryWrapper.getCustomSqlSegment());
        
        IPage<Order> orderPage = this.page(page, queryWrapper);
        
        System.out.println("查询到订单数量: " + orderPage.getTotal());
        
        // 转换为VO对象
        List<OrderVO> orderVOList = new ArrayList<>();
        for (Order order : orderPage.getRecords()) {
            OrderVO orderVO = convertToOrderVO(order);
            
            // 获取商品名称
            Product product = productMapper.selectById(order.getProductId());
            if (product != null) {
                orderVO.setProductName(product.getName());
            }
            
            orderVOList.add(orderVO);
        }
        
        // 创建VO分页对象
        Page<OrderVO> orderVOPage = new Page<>(pageNum, pageSize);
        orderVOPage.setRecords(orderVOList);
        orderVOPage.setTotal(orderPage.getTotal());
        
        return orderVOPage;
    }
    
    
    /**
     * 将订单实体转换为VO
     * @param order 订单实体
     * @return 订单VO
     */
    private OrderVO convertToOrderVO(Order order) {
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        
        // 设置前端展示字段
        orderVO.setOrderId(order.getId());
        orderVO.setTotalAmount(order.getTotalPrice());
        orderVO.setOrderStatus(order.getStatus());
        
        return orderVO;
    }
} 